import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    console.log('Request Config:', config)
    return config
  },
  error => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('Response:', response)
    return response
  },
  error => {
    console.error('Response Error:', error)
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          localStorage.removeItem('token')
          router.push('/login')
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          ElMessage.error(error.response.data?.message || '未知错误')
      }
    } else if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络连接失败，请检查服务器是否正常运行')
    } else {
      ElMessage.error('请求失败：' + error.message)
    }
    return Promise.reject(error)
  }
)

export const login = (credentials) => api.post('/auth/login', credentials)
export const getGreenhouses = () => api.get('/greenhouse/get')
export const getDevices = (greenhouseId) => api.get(`/devices/greenhouse/${greenhouseId}`)
export const getSensorData = (deviceId) => api.get(`/devices/${deviceId}/sensor-data`)
export const getPhotos = (deviceId) => api.get(`/camera/${deviceId}/photos`)
export const getCameraToken = () => api.get('/camera/token')
export const getLatestSensorData = (deviceId) => api.get(`/devices/${deviceId}/sensor-data/latest`)